package com.ruoyi.chat.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai/chat")
public class BaiduQianfanController {

    private static final Logger logger = LoggerFactory.getLogger(BaiduQianfanController.class);


    @Value("${baidu.qianfan.apikey}")
    private String apiKey;

    private static final String QIANFAN_API_URL = "https://qianfan.baidubce.com/v2/chat/completions";

    @PostMapping("/chat")
    public ResponseEntity<String> chatWithBaiduQianfan(@RequestBody Map<String, Object> userMessage) {
        // 1. 验证输入内容
        if (userMessage == null || !userMessage.containsKey("content")) {
            logger.error("请求缺少content字段");
            return ResponseEntity.badRequest()
                    .body("{\"error\":\"请求必须包含content字段\"}");
        }

        // 2. 获取并验证内容
        String userContent;
        try {
            userContent = userMessage.get("content").toString().trim();
            if (userContent.isEmpty()) {
                throw new IllegalArgumentException();
            }
        } catch (Exception e) {
            logger.error("content字段无效");
            return ResponseEntity.badRequest()
                    .body("{\"error\":\"content字段必须是有效字符串\"}");
        }

        logger.info("处理用户请求内容: {}", userContent);


        RestTemplate restTemplate = new RestTemplate();
        // 严格按照要求设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Host", "qianfan.baidubce.com");
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey); // 保持Bearer前缀

        // 严格按照示例构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "ernie-3.5-8k"); // 固定模型名称

        // 构建消息列表
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息（固定内容）
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "平台助手"); // 固定系统消息
        messages.add(systemMessage);

        // 用户消息（来自请求）
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", userContent);
        messages.add(userMsg);

        requestBody.put("messages", messages);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
        System.out.println("Request URL: " + QIANFAN_API_URL);
        System.out.println("Headers: " + headers);
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(QIANFAN_API_URL, entity, String.class);
            return ResponseEntity.ok(response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("{\"error\":\"调用百度千帆API失败: " + e.getMessage() + "\"}");
        }
    }
}